import React, { useState, useEffect, useCallback, } from 'react'
import { Col, Form, Input, Button, Row, Modal, InputNumber, Switch, message, Table, Select, Radio, } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import GroupTree from './components/groupTree'
import {
  fetchGroupTree,
  fetchGroups,
  addGroup,
  editGroup,
  delGroup,
  GroupBindingUser,
  fetchGroupType,
} from '@/services/group'
import { formItemLayout } from '@/utils/utils'
import { connect } from 'dva'

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select;
const supplierType = [
  {
    name: '门店',
    id: '4',
  },
  {
    name: '供应商',
    id: '3',
  },
  {
    name: '商户',
    id: '2',
  },
  {
    name: '平台',
    id: '0',
  },
  {
    name: '代理商',
    id: '6',
  },
  {
    name: '渠道商',
    id: '7',
  },
  {
    name: '运营商',
    id: '8',
  }
]

const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '状态',
    dataIndex: 'isDefault',
    key: 'isDefault',
    render: text => <span>{text == 0 ? '启用' : '锁定'}</span>,
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
  },
];

const MemberGroup = props => {
  const { form, role, dispatch } = props
  const { inform, userList, supplierList, storeList } = role
  const { getFieldDecorator } = form
  const [data, setData] = useState([])
  const [treeData, setTreeData] = useState([])
  const [record, setRecord] = useState([])
  const [visible, setVisible] = useState(false)
  const [isShow, setIsShow] = useState(false)
  const [userId, setUserId] = useState(null)
  const [btnType, setBtnType] = useState(null)
  // treeModalId
  const [modalTreeKey, setModalTreeKey] = useState(null)
  // 账户类型
  const [accountType, setAccountType] = useState(null)

  useEffect(() => {
    fetchTree()
    init()
    dispatch({
      type: 'role/fetchUsers',
    })
  }, [])

  const init = async (params = { supplierId: 1 }) => {
    const res = await fetchGroups(params)
    setData(res.data)
  }

  const fetchTree = async (params={supplierType: 1}) => {
    const res = await fetchGroupTree(params)
    setTreeData(res.data)
  }

  const addData = async params => {
    const res = await addGroup(params)
    message.info(res.msg) && init()
    setVisible(!visible)
    clear()
  }

  const editData = async params => {
    const res = await editGroup(params)
    message.info(res.msg) && init()
    setVisible(!visible)
    clear()
  }

  const delData = async params => {
    const res = await delGroup(params)
    await message.info(res.msg) && init()
  }

  const clear = () => {
    setModalTreeKey(null)
    setRecord([])
    setAccountType(null)
    dispatch({
      type: 'role/changeModelState',
      payload: {
        storeList: []
      }
    })
  }

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    // form.validateFields((err, values) => {
    //   console.log('Received values of form: ', values)
    //   const params = {
    //     supplierType: '2', //必填 登录信息中获取
    //     supplierId: '2', //必填 登录信息中获取
    //   }
    // })
  }

  // 新增/修改 模态框
  const handleStatus = (record = {}, type) => {    
    // if (type == 3 && inform) {
    //   dispatch({
    //     type: 'role/fetchSupplierType',
    //     payload: inform.supplierType,
    //   })
    //   dispatch({
    //     type: 'role/fetchStores',
    //     payload: {
    //       supplierId: inform.supplierId,
    //       pageSize: 999,
    //     },
    //   })
    // }
    setVisible(!visible);
    props.dispatch({
      type: 'role/changeModelState',
      payload: {
        inform: record,
      },
    });
  }

  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  
  // 按钮处理
  const handleBtn = type => {
    setBtnType(type)
    if (record.length != 1 && type != 1) return message.warning('请选择一项！');
    switch (type) {
      case 1: // 新增
        return handleStatus()
      case 3: // 编辑
        return handleStatus(record[0], type)
      case 4: // 删除
        return delData({
          id: record[0].id
        })
      case 6:
        return setIsShow(!isShow)
      default:
        break;
    }
  }

  // 新增/修改
  const handleGroup = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      const params = {
        parentId: modalTreeKey && modalTreeKey[0],
        isDefault: !values.isDefault ? '1' : '0',
      }
      btnType == 3 ? 
      editData({
        ...inform,
        ...values,
        parentId: modalTreeKey && modalTreeKey[0],
        isDefault: !values.isDefault ? '1' : '0',
      }) :
      addData({
        ...values,
        ...params,
      })
    })
  }

  // 用户绑定
  const bindingUser = () => {
    GroupBindingUser({
      userId: userId,
      id: record[0].id,
    })
    setIsShow(!isShow)
  }

  const cancelGroup = () => {
    setVisible(!visible)
    setAccountType(null)
    dispatch({
      type: 'role/changeModelState',
      payload: {
        storeList: []
      }
    })
  }
  
  // 获取详情
  const getTreeDeatil = (data, key) => 
    data.map(d => 
      d.id == key ? d : getTreeDeatil(d.childList, key)
    ).flat()
  
  // 账号类型
  const getSupplierType = val => {
    dispatch({
      type: 'role/fetchSupplierType',
      payload: val,
    })
    setAccountType(val)
  }
  // 所属商户
  const getSupplierId = val => {
    dispatch({
      type: 'role/fetchStores',
      payload: {
        supplierId: val,
        pageSize: 999,
      },
    })
  }

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setRecord(selectedRows)
    },
  };


  return (
    <PageHeaderWrapper>
      {/* <SearchBox handleReset={handleReset} handleSearch={handleSearch} /> */}
      <RenderButtom click={handleBtn} />
      <Table
        columns={columns}
        dataSource={hasSearchBtn ? data : []}
        rowSelection={rowSelection}
        rowKey={record => record.id}
      />
      {/* 绑定用户 */}
      <Modal
        visible={isShow}
        onOk={bindingUser}
        onCancel={() => setIsShow(!isShow)}
        destroyOnClose
      >
        用户绑定：<Select style={{width: 200}} onChange={val => setUserId(val)}>
          {userList.map(n => 
            <Option key={n.id} value={n.id} >{n.username}</Option>
          )}
        </Select>
      </Modal>
      {/* 新增删除 */}
      <Modal
        visible={visible}
        onOk={handleGroup}
        onCancel={cancelGroup}
        destroyOnClose
        title='新增/删除'
      >
        <Form {...formItemLayout}>
          <Form.Item label="中文名字">
            {getFieldDecorator('name', {
              initialValue: inform && inform.name,
              rules: [{
                required: true,
              }]
            })(<Input />)}
          </Form.Item>
          <Form.Item label="父分组">
            {getFieldDecorator('parentId', {
            })(<GroupTree 
              data={treeData}
              onSelect={id => setModalTreeKey(id)}  
              defaultSelectedKeys={[inform && String(inform.parentId)]}     
            />)}
          </Form.Item>
          <Form.Item label="机构组织类型">
            {getFieldDecorator('supplierType', {
              initialValue: inform && inform.supplierType,
            })(<Select
                onChange={getSupplierType}
              >
              {supplierType.map(n => 
                <Option key={n.id} value={n.id} >{n.name}</Option>
              )}
            </Select>)}
          </Form.Item>
          {accountType != 0 && <Form.Item label="机构组织名称">
            {getFieldDecorator('supplierId', {
              initialValue: inform && inform.supplierId ? (inform.supplierId).toString() : null,
            })(<Select
                showSearch  
                filterOption={(input, option) =>
                  option.props.children && option.props.children.indexOf(input) >= 0
                }
                onChange={getSupplierId}
            >
              {supplierList.map(n => 
                <Option key={n.id} value={n.id} >{n.companyName || n.operatorName}</Option>
              )}
            </Select>)}
          </Form.Item>}
          {(accountType == 4 || inform.supplierType == 4) && <Form.Item label="所属门店" >
            {getFieldDecorator('storeId', {
              initialValue: inform && inform.storeId ? (inform.storeId).toString() : null,
            })(<Radio.Group style={{height: 150, overflow: 'auto'}}>
                {
                  storeList.map(s => (
                    <Radio key={s.id} value={s.id}>{s.name}</Radio>
                  ))
                }
            </Radio.Group>)}
          </Form.Item>}
          <Form.Item label="英文名字">
            {getFieldDecorator('englishName', {
              initialValue: inform && inform.englishName,
            })(<Input />)}
          </Form.Item>
          <Form.Item label="描述">
            {getFieldDecorator('depict', {
              initialValue: inform && inform.depict,
            })(<Input />)}
          </Form.Item>
          <Form.Item label="编号">
            {getFieldDecorator('number', {
              initialValue: inform && inform.number,
            })(<Input />)}
          </Form.Item>
          <Form.Item label="排序">
            {getFieldDecorator('sort', {
              initialValue: inform && inform.sort,
            })(<InputNumber min={0} />)}
          </Form.Item>
          <Form.Item label="是否启用">
            {getFieldDecorator('isDefault', {
              initialValue: inform && inform.isDefault == 0 ? true : false,
              rules: [{
                required: true,
              }],
              valuePropName: 'checked',
            })(<Switch />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
    )
}

export default connect(({role}) => ({
  role,
}))(Form.create()(MemberGroup))
